import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import {
  Row,
  Col,
  Icon,
  Card,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
} from 'antd';
import numeral from 'numeral';
import {
  ChartCard,
  yuan,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from 'components/Charts';
import Trend from 'components/Trend';
import NumberInfo from 'components/NumberInfo';
import { getTimeDistance } from '../../utils/utils';
import EditableLinkGroup from 'components/EditableLinkGroup';
import OrderChart from '../Data/OrderChart';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Analysis.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const links = [
  {
    title: '商品管理',
    href: '/goods/goods-list',
  },
  {
    title: '订单管理',
    href: '/order/order-list',
  },
  {
    title: '用户管理',
    href: '/user/user-list',
  },
];

@connect(({ dashboard, dataAnalysis, orderChart, loading }) => ({
  dashboard,
  dataAnalysis,
  orderChart,
  loading: loading.effects['dashboard/fetchSalesData'],
}))
export default class Analysis extends Component {
  state = {
    rangePickerValue: getTimeDistance('today'),
    dateType : 0,  //0今天  1本周 2本月 3全年 4自定义时间段
  };

  componentDidMount() {
    this.props.dispatch({
      type: 'dataAnalysis/fetch',
    });
    this.props.dispatch({
      type: 'dashboard/fetchSalesData',
    });
    this.props.dispatch({
      type: 'dashboard/fetchPvData',
    });
    this.props.dispatch({
      type: 'dashboard/fetchPaymentData',
    });
    this.props.dispatch({
      type: 'dashboard/fetchUserActiveData',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'dashboard/clear',
    });
  }

  selectDate = type => {
    let dateType = 0;
    switch (type) {
      case 'today' :
        dateType = 0;
        break;
      case 'week' :
        dateType = 1;
        break;
      case 'month' :
        dateType = 2;
        break;
      case 'year' :
        dateType = 3;
        break;
      default :
        break;
    }
    this.setState({
      dateType: dateType,
      rangePickerValue: getTimeDistance(type),
    },()=>{
      const {rangePickerValue, currentTabKey} = this.state;
      this.props.dispatch({
        type: 'dataAnalysis/fetch',
        payload: {
          time_type: dateType,  //时间类型 0今天  1本周 2本月 3全年 4自定义时间段
          startTime: rangePickerValue[0].format('YYYY-MM-DD'),
          endTime: rangePickerValue[1].format('YYYY-MM-DD'),
        }
      });
    });
  };

  isActive = (type)=>{
    const {rangePickerValue} = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return;
    }
    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return styles.currentDate;
    }
  }

  render() {
    const { rangePickerValue, salesType, currentTabKey } = this.state;
    const { dashboard,dataAnalysis: {baseData}, orderChart, loading } = this.props;
    const {
      salesData,
      userActive,
      paymentData,
      pvData,
    } = dashboard;

    const salesExtra = (
      <div className={styles.salesExtraWrap}>
        <div className={styles.salesExtra}>
          <a className={this.isActive('today')} onClick={() => this.selectDate('today')}>
            今日
          </a>
          <a className={this.isActive('week')} onClick={() => this.selectDate('week')}>
            本周
          </a>
          <a className={this.isActive('month')} onClick={() => this.selectDate('month')}>
            本月
          </a>
          <a className={this.isActive('year')} onClick={() => this.selectDate('year')}>
            全年
          </a>
        </div>
        <RangePicker
          value={rangePickerValue}
          onChange={this.handleRangePickerChange}
          style={{ width: 256 }}
        />
      </div>
    );

    console.log('dashboard', dashboard);
    //console.log('123', [...new Set([1,2,3,4,2,1])]);

    const { orderData } = orderChart;

    const CustomTab = ({ data, currentTabKey: currentKey }) => (
      <Row gutter={8} style={{ width: 138, margin: '8px 0' }}>
        <Col span={12}>
          <NumberInfo
            title={data.name}
            subTitle="转化率"
            gap={2}
            total={`${data.cvr * 100}%`}
            theme={currentKey !== data.name && 'light'}
          />
        </Col>
        <Col span={12} style={{ paddingTop: 36 }}>
          <Pie
            animate={false}
            color={currentKey !== data.name && '#BDE4FF'}
            inner={0.55}
            tooltip={false}
            margin={[0, 0, 0, 0]}
            percent={data.cvr * 100}
            height={64}
          />
        </Col>
      </Row>
    );

    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 6,
      style: { marginBottom: 24 },
    };

    const paymentList = paymentData ? paymentData.detail.map(v=>{
      return {
        x : v.dateTime,
        y : v.value
      }
    }) : [];

    const pvList = pvData ? pvData.pvDetail.map(v=>{
      return {
        x : v.dateTime,
        y : v.value
      }
    }) : [];


    return (
      <Fragment>
          <Row gutter={24}>
              <Col xs={24}>
                  <Card
                      style={{ marginBottom: 24 }}
                      title="便捷导航"
                      bordered={false}
                      bodyStyle={{ padding: 0 }}
                  >
                      <EditableLinkGroup onAdd={() => {}} links={links} linkElement={Link} />
                  </Card>
              </Col>
          </Row>
          <Row>
            <Col>
              <div style={{'float':'right'}}>{salesExtra}</div>
            </Col>
          </Row>
          <Row gutter={24} style={{marginTop:'24px'}}>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="商城访客数"
                      action={
                          <Tooltip title="商城UV">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={baseData.uv || 0}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="下单笔数"
                      action={
                          <Tooltip title="包含未支持订单">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={baseData.order_total || 0}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="下单金额"
                      action={
                          <Tooltip title="包含未支持金额">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={'¥' + (baseData.order_price_total || 0)}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="付款订单数"
                      action={
                          <Tooltip title="已支付订单数量">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={baseData.order_pay_total || 0}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="付款金额"
                      action={
                          <Tooltip title="已支付订单金额">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={'¥' + (baseData.order_pay_price_total || 0)}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="访客下单转化率"
                      action={
                          <Tooltip title="订单数/uv">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={`${baseData.uv_order_rate || 0}%`}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="下单付款转化率"
                      action={
                          <Tooltip title="下单数量/已支付订单数">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={`${baseData.order_pay_rate || 0}%`}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
              <Col {...topColResponsiveProps}>
                  <ChartCard
                      bordered={true}
                      title="客单价"
                      action={
                          <Tooltip title="订单价格/订单数量">
                              <Icon type="info-circle-o" />
                          </Tooltip>
                      }
                      total={`¥${baseData.per_c_p || 0}`}
                      contentHeight={46}
                  >
                  </ChartCard>
              </Col>
          </Row>
          {/*
            <Row gutter={24}>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总营业额"
              action={
                <Tooltip title="商城总收入">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={() => <span>{ salesData.total || 0 }</span>}
              footer={<Field label="日均销售额" value={salesData.averagePerDay || 0} />}
              contentHeight={46}
            >
              <Trend flag={salesData.weekOverWeek > 0 ? "up" : "down" } style={{ marginRight: 16 }}>
                周同比<span className={styles.trendText}>{salesData.weekOverWeek || 0}%</span>
              </Trend>
              <Trend flag={salesData.dayOnDay > 0 ? "up" : "down" }>
                日环比<span className={styles.trendText}>{salesData.dayOnDay ||  0}%</span>
              </Trend>
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="访问量"
              action={
                <Tooltip title="PV">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={numeral(pvData.pv).format('0,0')}
              footer={<Field label="日访问量" value={numeral(pvData.todayPv).format('0,0')} />}
              contentHeight={46}
            >
              <MiniArea color="#975FE4" data={pvList} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="支付笔数"
              action={
                <Tooltip title="用户支付订单数">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={numeral(paymentData.payOrderTotal).format('0,0') || 0}
              footer={<Field label="转化率" value={((paymentData.payOrderTotal/paymentData.orderTotal)*100).toFixed(2) + "%"} />}
              contentHeight={46}
            >
              <MiniBar data={paymentList} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="用户活跃率"
              action={
                <Tooltip title="今日活跃/总用户数">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={(userActive.value || 0)  + '%'}
              footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                  <Trend style={{ marginRight: 16 }}>
                    周同比<span className={styles.trendText}>{userActive.weekOverWeek || 0}%</span>
                  </Trend>
                  <Trend>
                    日环比<span className={styles.trendText}>{userActive.dayOnDay || 0 }%</span>
                  </Trend>
                </div>
              }
              contentHeight={46}
            >
              <MiniProgress percent={userActive.value || 0} strokeWidth={8} target={20} color="#13C2C2" />
            </ChartCard>
          </Col>
        </Row>
          */}

        <Card loading={loading} bordered={false} bodyStyle={{ padding: 0 }}>
          <div className={styles.salesCard}>
            <OrderChart dispatch={ this.props.dispatch} data={orderData} type={['order','payOrder']}  />
          </div>
        </Card>
      </Fragment>
    );
  }
}
